package com.ab.apites;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Thread(new Runnable() {
            @Override
            public void run() {
                performLogin();
            }
        }).start();
    }

    private void performLogin() {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("username", "cs12345")
                .add("password", "123456")
                .add("uuid", UUID.randomUUID().toString())
                .build();

        Request request = new Request.Builder()
                .url("http://192.168.8.8:8763/app/login")
                .post(body)
                .build();

        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            String result = response.body().string();
            Gson gson = new Gson();
            WebResult web = gson.fromJson(result,WebResult.class);
            Object ob = web.getData();
            String jsonstring = gson.toJson(ob);
            JsonObject o = gson.fromJson(jsonstring,JsonObject.class);
            List<DeviceTblEntity> retList = gson.fromJson(o.get("devices").toString(),new TypeToken<List<DeviceTblEntity>>(){}.getType());
            System.out.println("===>"+retList.size());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
